package com.kehao.leetcode.algorithm;

import org.junit.After;
import org.junit.Test;

import java.util.HashSet;

import static org.junit.Assert.assertEquals;

//https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
public class Solution3 {
    public int lengthOfLongestSubstring(String s) {
        char[] charArray = s.toCharArray();
        int maxLength = 0;
        if(charArray.length==0) return 0;
        if(charArray.length==1) return 1;

        HashSet<Character> set = new HashSet<Character>();
        set.add(charArray[0]);
        int left = 0 ,right = 1;
        for (left = 0; left<charArray.length;left++){
            for(;right<charArray.length;right++){
                if(!set.contains(charArray[right])){
                    set.add(charArray[right]);
                    maxLength = Math.max(maxLength,set.size());
                }else {
                    break;
                }
            }
            set.remove(charArray[left]);
        }

        return maxLength;
    }


    @Test
    public void myTest1(){
        String s = "a";
        assertEquals(lengthOfLongestSubstring(s),1);
    }

    @Test
    public void myTest2(){
        String s = "abc";
        assertEquals(lengthOfLongestSubstring(s),3);
    }

    @Test
    public void myTest3(){
        String s = "";
        assertEquals(lengthOfLongestSubstring(s),0);
    }

    @Test
    public void myTest4(){
        String s = "dvdf";
        assertEquals(lengthOfLongestSubstring(s),3);
    }

    @Test
    public void myTest5(){
        String s = "pwwkew";
        assertEquals(lengthOfLongestSubstring(s),3);
    }

    @Test
    public void myTest6(){
        String s = "abcabcbb";
        assertEquals(lengthOfLongestSubstring(s),3);
    }

    @Test
    public void myTest7(){
        String s = "aab";
        assertEquals(lengthOfLongestSubstring(s),2);
    }
}
